﻿using System;
using System.IO;
using UnityEngine;

namespace UGlue
{
    public class LogFile
    {
        private string Path;

        public LogFile Enable(string logPath = null) {
            Path = String.IsNullOrEmpty(logPath) ? Application.persistentDataPath + "/log.ext" : logPath;
            Application.logMessageReceivedThreaded += LogCallback; //监听log系统日志
            AppDomain.CurrentDomain.UnhandledException += _OnUnresolvedExceptionHandler;//监听app异常退出
            m_FileInfo = new FileInfo(Path);
            return this;
        }

        public LogFile Disable() {
            Application.logMessageReceivedThreaded -= LogCallback;
            System.AppDomain.CurrentDomain.UnhandledException -= _OnUnresolvedExceptionHandler;
            return this;
        }

        private void _OnUnresolvedExceptionHandler(object sender, UnhandledExceptionEventArgs e) {
            Debug.LogError(sender + ", ErrMsg：" + e);
        }


        private void LogCallback(string condition, string stackTrace, LogType type) {
            WriteIntoFile(System.DateTime.Now.ToString("yyyy.mm.dd hh:mm:ss  ") + condition + "\n" + stackTrace + "\n");
        }

        private int m_iLogs = 0;
        private long max_size = 500 * 1024 * 1024;//500MB
        private FileInfo m_FileInfo;

        public void WriteIntoFile(string message) {
            if (++m_iLogs > 1000 && m_FileInfo.Length > max_size) {
                m_iLogs = 0;
                File.Delete(Path);
            }
            File.AppendAllText(Path, message);//TODO 这里不要每次都读取沙盒地址
        }
    }
}

